<template>
  <div>
    <p>vuex状态管理</p>
    <div>
      <!-- 在html中直接使用$store获取值 -->
      <p>
        我们的菜单有： <span>共有{{ $store.getters.cdlength }}道菜</span>
      </p>
      <p v-for="(item, ind) in cd" :key="ind">
        菜名: <span>{{ item.name }}</span> | 价格：{{ item.pri }}
      </p>
    </div>
    <div>
      <p>添加菜单：</p>
      <p>
        菜名:<input type="text" v-model="cmin" />|
        价格：<input type="text"  v-model="cpri"  />
        <button @click="add">增加</button>
      </p>
    </div>
    <div>
      <button @click="setAge(1)">无聊中</button>
      <p>
        <button @click="gor">路由传参跳转</button>
      </p>
    </div>
  </div>
</template>

<script lang='ts'>
import { reactive, toRefs } from "vue";
import { useStore, mapActions } from "vuex";
import {useRouter} from 'vue-router'
export default {
  setup() {
    let state = reactive({
      cmin: "",
      cpri: "",
    });

    //通过 hook 拿到store 的内容
    let store = useStore();
    let cd = store.state.cd;

    //获取mapActions
    let actions={ ...mapActions(['addc','setAge']) }
    console.log(actions)

    
    let add = () => {
      let plus = {
        name: state.cmin,
        pri: Number(state.cpri) ,
      };
      if (plus.pri&&typeof plus.pri == "number") {
        store.commit("addc", plus);
        state.cmin = "";
        state.cpri = "";
      } else {
        alert("价格必须为数字");
      }
    };

    let router=useRouter()
    let gor=()=>{
      router.push({name:'/ccrouter',query:{id:888}})
    }
    

    //可以直接导出mapActions方法
    return {
      cd,
      ...toRefs(state),
      add,gor,
      ...mapActions(["setAge"]),
    };
  },
};
</script>

<style>
</style>